#!/usr/bin/env bash

source ../../lib/shell/common.sh

function nvme_trim_check_test() {
    local discard_granularity
    local no_support_trim_devinfo
    local err_msg=""
    echo "Nvme trim check test."
    for nd in $NVME_DEVS;do
        discard_granularity=`cat /sys/block/"${nd#*/dev/}"/queue/discard_granularity`
        no_support_trim_devinfo=`lsblk --discard|grep -w "${nd#*/dev/}"|awk '$3=="0B" || $4=="0B" {print}'`
        if [ "${discard_granularity}" == "0" ];then
            err_msg="${err_msg}/sys/block/${nd#*/dev/}/queue/discard_granularity is 0, trim check failed.\n"
        else
            echo "Trim check: cat /sys/block/${nd#*/dev/}/queue/discard_granularity successfully."
        fi

        if [ -n "${no_support_trim_devinfo}" ];then
            err_msg="${err_msg}${nd#*/dev/} do not support trim.\n"
        else
            echo "Trim check: lsblk --discard |grep ${nd#*/dev/} successfully."
        fi
    done
    [ -n "$err_msg" ] && { echo "Exist devices do not support trim.";echo -e "$err_msg";test_fail; }
}
# # # # # # # # # # # # # # main # # # # # # # # # # # # # #
echo "Nvme trim function check for all nvme disks."
nvme_dev_check
nvme_trim_check_test
test_pass
